<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" class="main-search">
      <el-form-item label="渠道名称" prop="channelName">
        <el-input
          v-model="queryParams.channelName"
          placeholder="请输入渠道名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="渠道描述" prop="channelDescribe">
        <el-input
          v-model="queryParams.channelDescribe"
          placeholder="请输入渠道描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="channelDataConfList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="渠道名称" align="center" prop="channelName" width="150"/>
      <el-table-column label="渠道描述" align="center" prop="channelDescribe" width="150"/>
      <el-table-column label="渠道来源名称" align="center" prop="channelIdentity" width="150"/>
<!--      <el-table-column label="渠道标识" align="center" prop="channelSource" width="150"/>-->
      <el-table-column label="管理员" align="center" prop="glInfo"/>
      <el-table-column label="业务员" align="center" prop="ywInfo"/>
      <el-table-column label="是否开启" align="center" prop="isOpen">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isOpen"
            active-value="1"
            inactive-value="0"
            @change="changeOpenChannel(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['channel:channelDataConf:edit']"
          >API配置
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据渠道管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="渠道名称" prop="channelName">
          <el-input v-model="form.channelName" placeholder="请输入渠道名称"/>
        </el-form-item>
        <el-form-item label="渠道描述" prop="channelDescribe">
          <el-input v-model="form.channelDescribe" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="渠道标识名称" prop="channelIdentity">
          <el-input v-model="form.channelIdentity" placeholder="请输入渠道标识名称"/>
        </el-form-item>
        <el-form-item label="渠道唯一标识" prop="channelSource">
          <el-input v-model="form.channelSource" placeholder="请输入渠道唯一标识" :disabled="form.id != null"/>
        </el-form-item>
        <el-form-item label="管理员" prop="glList">
          <el-select v-model="form.glList" placeholder="请选择管理" multiple>
            <el-option
              v-for="dict in glUserList"
              :key="dict.userId"
              :label="dict.nickName"
              :value="dict.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务员">
          <div class="serve-person">
            <div class="serve-person-form-item" v-for="(item, index) in form.ywList" :key="item.key">
              <div class="item-op-icon" v-show="form.ywList.length > 1"
                   @click="removeCooperate(index)">
                <img class="item-delete-icon" src="@/assets/project/icon-minus.png" alt="">
              </div>
              <div class="item-form-box dialog-form" :style="{ '--form-item-width': '33px' }">
                <el-form-item label="人员" :prop="`ywList.${index}.userId`" label-width="70px" :rules="{
                      required: true, message: '人员不能为空', trigger: 'blur'
                    }">
                  <el-select v-model="item.userId" placeholder="请选择">
                    <el-option v-for="dict in ywUserList" :key="dict.userId" :label="dict.nickName"
                               :value="dict.userId"
                               :disabled="form.ywList.some(i => i.userId === dict.userId)"></el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div class="item-form-box dialog-form" :style="{ '--form-item-width': '33px' }">
                <el-form-item label="数量" :prop="`ywList.${index}.number`" label-width="60px" :rules="{
                                    required: true, message: '数量不能为空', trigger: 'blur'
                                  }">
                  <el-input-number v-model="item.number" :min="0"
                                   :max="1000" :controls="false" placeholder="请输入上限0-1000">
                  </el-input-number>
                </el-form-item>
              </div>

              <div class="item-form-box dialog-form" :style="{ '--form-item-width': '33px' }">
                <el-form-item label="类型" :prop="`ywList.${index}.disType`" label-width="60px" :rules="{
                                    required: true, message: '数量不能为空', trigger: 'blur'
                                  }">
                  <el-select v-model="item.disType" placeholder="请选择">
                    <el-option v-for="dict in disTypeList" :key="dict.value" :label="dict.label"
                               :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </div>

            </div>
            <div class="serve-person-form-item" @click="addYwUser">
              <div class="add-btn">
                <img class="add-btn-icon" src="@/assets/project/icon-add.png" alt="">
                <span class="add-icon-text">增加</span>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addChannelDataConf,
  delChannelDataConf,
  getChannelDataConf,
  listChannelDataConf,
  updateChannelDataConf,
  updateOpenConf
} from "@/api/channel/channelDataConf";
import {changeUserLocked, changeUserStatus, channelUser} from "@/api/system/user";
import {getUserList} from "@/api/customerPool/customerPool";

export default {
  name: "ChannelDataConf",
  data() {
    return {
      disTypeList: [
        {
          label: '天',
          value: 'day'
        },
        {
          label: '月',
          value: 'month'
        },
        {
          label: '年',
          value: 'year'
        }
      ],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据渠道管理表格数据
      channelDataConfList: [],
      glUserList: [],
      ywUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        channelName: undefined,
        channelDescribe: undefined,
        isOpen: undefined,
        createId: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          {required: true, message: "id不能为空", trigger: "blur"}
        ],
        channelName: [
          {required: true, message: "渠道名称不能为空", trigger: "blur"}
        ],
        channelSource: [
          {required: true, message: "渠道唯一标识不能为空", trigger: "blur"}
        ],
        channelIdentity: [
          {required: true, message: "渠道标识名称不能为空", trigger: "blur"}
        ],
        glList: [
          {required: true, message: "管理员不能为空", trigger: ["blur", "change"]}
        ],
        ywList: [
          {required: true, message: "业务员不能为空", trigger: ["blur", "change"]}
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getGlList();
  },
  methods: {

    // 新增业务员
    addYwUser() {
      this.form.ywList.push({
        id: undefined,
        userId: undefined,
        number: undefined,
        disType: 'day',
        key: Date.now()
      })
    },

    // 移除信息
    removeCooperate(index) {
      this.form.ywList.splice(index, 1);
    },

    getGlList() {
      channelUser().then(response => {
        this.glUserList = response.data;
      })
      const query = {
        type: "1"
      }
      getUserList(query).then(response => {
        this.ywUserList = response.data;
      })
    },

    /** 查询数据渠道管理列表 */
    getList() {
      this.loading = true;
      listChannelDataConf(this.queryParams).then(response => {
        this.channelDataConfList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 渠道数据状态
    changeOpenChannel(row) {
      let text = row.isOpen == 1 ? "开启" : "锁定";
      this.$modal.confirm('确认要"' + text + '""' + row.channelName + '"吗？').then(function () {
        return updateOpenConf({"id": row.id, "isOpen": row.isOpen});
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.isOpen = row.isOpen == 0 ? 1 : 0;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        channelName: undefined,
        channelDescribe: undefined,
        channelSource: undefined,
        channelIdentity: undefined,
        isOpen: undefined,
        createId: undefined,
        status: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        glList: [],
        ywList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据渠道管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getChannelDataConf(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改数据渠道管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          const data = {
            ...this.form
          }
          if (this.form.id != null) {
            updateChannelDataConf(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addChannelDataConf(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据渠道管理编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delChannelDataConf(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('channel/channelDataConf/export', {
        ...this.queryParams
      }, `channelDataConf_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.messageCard {
  overflow-x: hidden;
  overflow-y: scroll;
  word-break: break-all;
  width: 400px;
  max-height: 100px;
  text-align: left;
  float: left;
  text-align: left;
  text-overflow: ellipsis;
  color: #313131;
}

.messageCard::-webkit-scrollbar {
  width: 4px;
}

.messageCard::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.2);
}

.messageCard::-webkit-scrollbar-track {
  border-radius: 0;
  background: rgba(0, 0, 0, 0.1);
}


.serve-person {
  .serve-person-form-item {
    position: relative;
    padding-left: 32px;
    border-left: 1px solid #E3E6E5;
    display: flex;

    &::before {
      content: "";
      width: 20px;
      height: 1px;
      background: #E3E6E5;
      position: absolute;
      left: 0;
      top: 16px;
    }

    &:last-child {
      border: none;

      &::after {
        content: "";
        width: 550px;
        height: 16px;
        border-left: 1px solid #E3E6E5;
        position: absolute;
        left: 0;
        top: 0;
      }
    }

    .item-op-icon {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 20px;
      height: 32px;
      cursor: pointer;

      .item-delete-icon {
        width: 16px;
        height: 16px;
      }
    }
  }

  .add-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 80px;
    height: 32px;
    border-radius: 4px;
    border: 1px solid #E3E6E5;
    cursor: pointer;
    user-select: none;

    .add-btn-icon {
      width: 16px;
      height: 16px;
    }

    .add-btn-text {
      margin-left: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
    }
  }
}
</style>
